#include <stdlib.h>

#include "Galaxy.h"
#include "Quadrant.h"
#include "LongRangeScan.h"
#include "Model.h"
#include "Render.h"

void Galaxy::Init(Quadrant* aQuad, LongRangeScan* lrs)
{
	quadrant = aQuad;
	LRS = lrs;
	spawnQuads();
	fillGrid();
	Warp(XY(rand()%BOARD_SIZE, rand()%BOARD_SIZE));
	PrepDraw();
	cursor = currentQuad;
}

void Galaxy::spawnQuads()
{
	bool StationMinimum = false;
	int randomNumber;
	QuadInfo info;

	for(int i=0;i<NUM_BOARD_PIECES;++i)
	{
		//enemies
		randomNumber = rand()%100;
		if(randomNumber < CHANCE_1_ENEMIES)
			info.Enemies = 1;
		if(randomNumber < CHANCE_2_ENEMIES)
			info.Enemies = 2;
		if(randomNumber < CHANCE_3_ENEMIES)
			info.Enemies = 3;
		//station
		randomNumber = rand()%100;
		if(randomNumber < CHANCE_1_STATION)
		{
			info.Stations = 1;
			StationMinimum = true;
		}
		//stars
		randomNumber = rand()%MAX_STARS;
		info.Suns = randomNumber;
		quad[i].Init(info);
	}
	if(!StationMinimum)
		quad[rand()%NUM_BOARD_PIECES].AddStation();
}

void Galaxy::fillGrid()
{
	Render* ren = Render::getInstance();
	SpriteInfo info;
	info.numTextures = 1;
	info.reference = ren->LoadTexture("Textures/Blank Tile.png", 45, 45);

	for(int i=0;i<NUM_BOARD_PIECES;++i)
		quad[i].InitSprite(info);

	int count=0;
	for(int i=0;i<BOARD_SIZE;++i)
		for(int j=0;j<BOARD_SIZE;++j, count++)
			square[i][j] = &quad[count];
}

void Galaxy::Warp(XY q)
{
	quadrant->Load((Quad*)square[q.x][q.y]);
	currentQuad = q;
	Scan();
}

void Galaxy::Scan()
{
	Quad* scan[LRS_RANGE];

	scan[0] = (Quad*)getNorthEast(currentQuad);
	scan[1] = (Quad*)getNorth(currentQuad);
	scan[2] = (Quad*)getNorthWest(currentQuad);
	scan[3] = (Quad*)getEast(currentQuad);
	scan[4] = (Quad*)getWest(currentQuad);
	scan[5] = (Quad*)getSouthEast(currentQuad);
	scan[6] = (Quad*)getSouth(currentQuad);
	scan[7] = (Quad*)getSouthWest(currentQuad);

	LRS->Load(scan);
}

void Galaxy::Update(MouseInfo info)
{
	XY mouse = SquareOver(info.pos);
	if(cursor != mouse)
	{
		getSquare(cursor)->setState(NOT_SELECTED);
		cursor = mouse;
		getSquare(cursor)->setState(SELECTED);
	}
	if(info.Clicked)
	{
		if(cursor != currentQuad)
		{
			currentQuad = cursor;
			quadrant->Load( (Quad*)getSquare(cursor) );
		}
		//Model::getInstance()->SetState(notwarp);
	}
}